import axios from 'axios'
import { stringify } from 'query-string'
import config from 'config/config'

axios.defaults.baseURL = config.apiUrl
axios.defaults.headers.post['Content-Type'] = 'application/json'

axios.interceptors.request.use(req => {
  console.log('request', req)
  return req
}, error => {
  throw (error)
})

axios.interceptors.response.use(res => {
  console.log('request data', res)
  return res.data
}, error => {
  throw (error)
})

const createRequest = (type) => {
  return (url, opts?: any) => {
    console.log('url', url, ' ,opts: ', opts)

    if (type === 'put' || type === 'post') {
      return axios[type](url, opts, { baseURL: config.apiUrl })
    } else {
      return axios[type](url, { baseURL: config.apiUrl, ...opts })
    }
  }
}

const withAxios = {
  get: createRequest('get'),
  post: createRequest('post'),
  put: createRequest('put'),
  delete: createRequest('delete'),
  axios
}

export default withAxios
